package cjj;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@WebServlet("/admin/deleteBook")
public class AdminDeleteBookServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer adminId = (Integer) request.getSession().getAttribute("adminId");
        if (adminId == null) {
            response.sendRedirect("/admin/login");
            return;
        }

        try {
            Integer bookId = Integer.valueOf(request.getParameter("bookId"));

            try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025", "root", "root");
                 PreparedStatement stmt = conn.prepareStatement("DELETE FROM book WHERE BOOK_ID=?")) {
                stmt.setInt(1, bookId);
                int rows = stmt.executeUpdate();

                HttpSession session = request.getSession();
                if (rows > 0) {
                    session.setAttribute("message", "图书删除成功");
                    session.setAttribute("messageType", "success");
                } else {
                    session.setAttribute("message", "未找到指定图书，删除失败");
                    session.setAttribute("messageType", "error");
                }
            }

            response.sendRedirect(request.getContextPath() + "/admin/manageBooks");
        } catch (Exception e) {
            e.printStackTrace();
            HttpSession session = request.getSession();
            session.setAttribute("message", "删除图书失败: " + e.getMessage());
            session.setAttribute("messageType", "error");
            response.sendRedirect(request.getContextPath() + "/admin/manageBooks");
        }
    }
}